<template>
	<div class="root rounded-lg mb-2 p-1">
		<div v-for="(item, index) in tokenData" :key="index" class="token-display">
		
			<p><span>NFT Name:</span> {{ item.nftName }}</p>
			<p><span>uri:</span> {{ item.uri}}</p>
			<p><span>img:</span> {{ item.img}}</p>
			<p><span>Nft Symbol:</span> {{ item.nftSymbol}}</p>
			<p><span>Price:</span> {{ item.priceUi }}</p>
			<p><span>totalMinted:</span> {{ item.totalMinted}}</p>
			<p><span>limit:</span> {{ item.limit}}</p>
	
			<!-- 添加按钮 -->
			<button @click="navigateToUseNftPage(item)">Mint NFT</button>
		
		</div>
	</div>
</template>

<script setup>
    import {
        ref,
        onMounted
    } from 'vue';
    import {
        PublicKey,
        Connection,
		LAMPORTS_PER_SOL
    } from "@solana/web3.js";
    import {
        useWorkspace
    } from "../vuex/store";
    import {
        Metaplex,
        keypairIdentity,
        bundlrStorage,
        Metadata
    } from "@metaplex-foundation/js";
    import bs58 from 'bs58';
    import {
        BN
    } from "bn.js";
    import {
        useRouter
    } from 'vue-router';
    import {
        ASSOCIATED_PROGRAM_ID,
        TOKEN_PROGRAM_ID,
        associatedAddress
    } from "@coral-xyz/anchor/dist/cjs/utils/token";
    import {
        ENV,
        TokenListProvider
    } from "@solana/spl-token-registry";
    import * as anchor from "@coral-xyz/anchor";
	import store from '../vuex';
    
    // 定义响应式变量来存储代币数据
    const tokenData = ref([]);
    const router = useRouter();

    // 定义 loadData 函数
    async function loadData() {
    
		const workspaceValue = store.state.workspace.value;
        if (!workspaceValue) {
            console.error('Workspace is not initialized.');
            return;
        }
        const {
            connection,
            program,
            wallet,
            provider
        } = workspaceValue;
        const mx = Metaplex.make(connection);

        let img = '';
      
        try {
            const owner = provider.wallet.publicKey.toBase58();
            const ownerkey = provider.wallet.publicKey;

            let gain = false;

            const data = await program.account.cardInfo.all();

            const tokenDataArray = await Promise.all(data.map(async (item) => {
                const collectionMint = item.account.collectionMint; 

                const user = anchor.web3.PublicKey.findProgramAddressSync([
                    ownerkey.toBytes(), 
                    collectionMint.toBytes()
                ], program.programId)[0];

         
				const feeRecipient = item.account.feeRecipient;
			
		
				const totalMinted = item.account.totalMinted.toString();
                const price = item.account.price.toString();
                const supply = item.account.supply.toString();
                const limit = item.account.limit.toString();

                const priceUi = price/LAMPORTS_PER_SOL;
                const asset = await mx.nfts().findByMint({
                    mintAddress: collectionMint
                });
                const nftName = asset.name;
                let uri = asset.uri;
                const nftSymbol = asset.symbol;
				
				const alternativeUri = uri.replace('https://ipfs.io', 'https://cloudflare-ipfs.com');
			

				try {

					const response = await fetch(uri);
					const contentType = response.headers.get('Content-Type');

					if (contentType.includes('application/json')) {
					const jsonContent = await response.json();
					img = jsonContent.image;
					} else if (contentType.includes('image')) {
					img = '';
					} else {
					img = '';
				}
				} catch (error) {
				// 捕获错误
				}

            

                const authority = item.account.authority;
                if (owner == authority.toBase58()) {
                    gain = true;
                } else {
                    gain = false;
                }
                    
                return {
                    nftName: nftName,
                    img: img,
                    uri: uri,
                    priceUi: priceUi,
                    nftSymbol: nftSymbol,
                    price: price,
					feeRecipient,
					totalMinted,
                    collectionMetadata: item.account.collectionMetadata,
                    collectionMint: collectionMint,
                    authority: authority,
                    gain: gain,
                    supply: supply,
                    limit: limit,
                };
            }));
            tokenDataArray.sort((b, a) => b.time - a.time);
            tokenData.value = tokenDataArray;

        } catch (error) {
            console.error('Failed to load data:', error);
        }
    }

    onMounted(() => {
        store.commit('initWorkspace', {
            callback: () => {
                loadData(); // 这里不需要使用 this，直接调用 loadData 函数即可
            }
        });
    });

    //用户
    function formatDate(date) {
        date = new Date(parseInt(date));
        return new Intl.DateTimeFormat('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
        }).format(date);
    }

    const navigateToUseNftPage = (item) => {
        const pinData = JSON.stringify(item);
        router.push({
            path: '/mintnft',
            query: {
                'pinData': pinData
            }
        });
    };


</script>
<style scoped>
	/* 设置组件的根元素背景颜色和文本颜色 */
	.root {
		background-color: #f0f0f0 !important;
		/* 浅灰色背景 */
		color: #333 !important;
		/* 深灰色文本 */
		overflow: auto;
		width: 80%;
		max-width: 600px;
		height: 80%;
	}

	/* 设置 token 显示区域的样式 */
	.token-display {
		background-color: #fff !important;
		/* 白色背景 */
		border: 1px solid #ddd !important;
		/* 边框颜色 */
		padding: 16px !important;
		/* 内边距 */
		margin: 8px 0 !important;
		/* 外边距 */
		border-radius: 8px !important;
		/* 圆角边框 */
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1) !important;
		word-break: break-all;
		/* 添加阴影效果 */
	}

	/* 为了提高可读性，您可以为文本添加一些间距 */
	p {
		line-height: 1.6 !important;
		/* 行高 */
		margin-bottom: 16px !important;
		/* 段落之间的间距 */
	}
	span{
		font-weight: bold;
		color: #444444;
	}
</style>